<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小企业物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996 15899929162
// +----------------------------------------------------------------------
namespace app\common\dao\property\basic;

use app\common\dao\BaseDao;
use app\common\model\property\basic\PropertyUnitModel;
use app\traits\CategoryDao;

class PropertyUnitDao extends BaseDao
{

    use CategoryDao;

    /**
     * @return PropertyUnitModel
     */
    protected function getModel(): string
    {
        return PropertyUnitModel::class;
    }

    public function search(array $where, int $propertyId = null)
    {
        return $this->getModel()::getDB()
            ->when($propertyId !== null, function ($query) use ($propertyId) {
                $query->where('property_id', $propertyId);
            })
            ->when(isset($where['pid']) && $where['pid'] !== '', function ($query) use ($where) {
                $query->where('pid', (int)$where['pid']);
            })
            ->when(isset($where['is_show']) && $where['is_show'] !== '', function ($query) use ($where) {
                $query->where('is_show', $where['is_show']);
            })
            ->when(isset($where['keywords']) && $where['keywords'] !== '', function ($query) use ($where) {
                $query->whereLike('unit_name|remark', '%' . trim($where['keywords']) . '%');
            });
    }

    public function unitNameExists(int $propertyId, string $roomName, int $pid, int $except = null)
    {
        return $this->search(['property_id' => $propertyId])
                ->where('unit_name', $roomName)
                ->when($pid !== null, function ($query) use ($pid) {
                    $query->where('pid', $pid);
                })
                ->when($except !== null, function ($query) use ($except) {
                    $query->where('id', '<>', $except);
                })
                ->count() > 0;
    }

    /**
     * 获取全部楼栋
     * @param $propertyId
     * @param array $where
     * @param $field
     * @return array|\think\Collection|\think\db\BaseQuery[]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-06-12 22:18
     */
    public function getAll(array $where, $propertyId = null, $field = '*')
    {
        $query = $this->search($where, $propertyId);
        return $query->field($field)->order($this->getPk() . ' DESC')->select();
    }
}
